<?php

class Talktangle_Model_DbTable_Crosstangles extends Engine_Db_Table
{
    protected $_rowClass = 'Talktangle_Model_Crosstangle';
    
   /**
   * @const SET IMAGE WIDTH
   */
  const IMAGE_WIDTH = 720;
  /**
   * @const SET IMAGE HIGHT
   */
  const IMAGE_HEIGHT = 720;
  /**
   * @const SET THUMB IMAGE WIDTH
   */
  const THUMB_WIDTH = 140;
  /**
   * @const SET THUMB IMAGE HIGHT
   */
  const THUMB_HEIGHT = 160;
  public function uploadPhoto($params,$file){
    if ($file instanceof Storage_Model_File) {
      $params['file_id'] = $file->getIdentity();
    } 
    else 
    {
      //Get image info and resize
      $name = basename($file['tmp_name']);
      $path = dirname($file['tmp_name']);
      $extension = ltrim(strrchr($file['name'], '.'), '.');

       
      $mainName = $path . '/m_' . $name . '.' . $extension;
      $thumbName = $path . '/t_' . $name . '.' . $extension;
        
      $image = Engine_Image::factory();
      $image->open($file['tmp_name'])
              ->resize(self::IMAGE_WIDTH, self::IMAGE_HEIGHT)
              ->write($mainName)
              ->destroy();
     
        
      $image = Engine_Image::factory();
      $image->open($file['tmp_name'])
              ->resize(self::THUMB_WIDTH, self::THUMB_HEIGHT)
              ->write($thumbName)
              ->destroy();
      
      $thumbW = $image->getWidth();
      $thumbH = $image->getHeight();
        
      //Store photos
      $photo_params = array(
          'parent_id' => 0,
          'parent_type' => 'talktangle_crosstangle',
      );
      
     
      
      $photoFile = Engine_Api::_()->storage()->create($mainName, $photo_params);
      $photoFile->save();
      
      $thumbFile = Engine_Api::_()->storage()->create($thumbName, $photo_params);
      $thumbFile->save();
      $photoFile->bridge($thumbFile, 'thumb.normal');
      
      //Storage full size image.
      if (Engine_Api::_()->getApi('settings', 'core')->getSetting('photo.fullsize.storage', 0)) {
          $fullsizeName = $path . '/o_' . $name . '.' . $extension;
          $image = Engine_Image::factory();
          $image->open($file['tmp_name'])
                  //->resize(self::THUMB_WIDTH, self::THUMB_HEIGHT)
                  ->write($fullsizeName)
                  ->destroy();
          $fullsizeFile = Engine_Api::_()->storage()->create($fullsizeName, $photo_params);
          $fullsizeFile->save();
          $photoFile->bridge($fullsizeFile, 'fullsize.normal');
          @unlink($fullsizeName);          
          //$fullsizeFile->width = $fullW;
          //$fullsizeFile->height = $fullH;
          
      }
    
      //Remove temp files
      @unlink($mainName);
      @unlink($thumbName);
        
      return $photoFile;

      
    } 
  }
}